package com.backend.plat.sa.controller;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.backend.dto.OrganizationalDto;
import com.backend.dto.PermissionMenusDto;
import com.google.gson.reflect.TypeToken;
import com.oxygen.constants.Constant;
import com.oxygen.dto.ApiFinalResponse;
import com.oxygen.enums.BackendApiMethodEnum;
import com.oxygen.util.JsonUtil;
import com.oxygen.web.WebHelper;

/**
 * 前台用户管理
 * 
 * @author Daniel
 */
@Controller
@RequestMapping(value = "/menus")
public class BackendMenusAction extends BaseAction {

	@RequestMapping(value = "/search")
	public String search(HttpServletRequest req, HttpServletResponse rsp) {
		WebHelper.setRequestAttributesFromRequestParam(req);
		return "/menus/search";
	}

	@RequestMapping(value = "/list")
	public String list(HttpServletRequest req, HttpServletResponse rsp) {
		Map<String, Object> appendMap = new HashMap<String, Object>();
		appendMap.put(Constant.PAGE, req.getParameter(Constant.PAGE));
		appendMap.put(Constant.PAGE_SIZE, req.getParameter(Constant.PAGE_SIZE));
		String json = this.callApi(BackendApiMethodEnum.USER_GETMENU, appendMap, req);
		Type type = new TypeToken<Map<String, ApiFinalResponse<List<PermissionMenusDto>>>>() {
		}.getType();
		Map<String, ApiFinalResponse<List<PermissionMenusDto>>> retMap = JsonUtil.jsonToObject(json, type);
		
		if (retMap != null) {
			retMap.get(BackendApiMethodEnum.USER_GETMENU.getCode()).getResults();
			req.setAttribute("apiRsp", retMap.get(BackendApiMethodEnum.USER_GETMENU.getCode()));
			
		}
		WebHelper.setRequestAttributesFromRequestParam(req);
		return "/menus/list";
	}

	@RequestMapping(value = "/edit/{id}")
	public String edit(@PathVariable String id, HttpServletRequest req, HttpServletResponse rsp) {
		Map<String, Object> appendMap = new HashMap<String, Object>();
		appendMap.put("id", id);
		String json = this.callApi(BackendApiMethodEnum.USER_GETMENU, appendMap, req);
		Type type = new TypeToken<Map<String, ApiFinalResponse<OrganizationalDto>>>() {
		}.getType();
		Map<String, ApiFinalResponse<OrganizationalDto>> retMap = JsonUtil.jsonToObject(json, type);

		if (retMap != null && retMap.get(BackendApiMethodEnum.USER_GETMENU.getCode()) != null) {
			req.setAttribute("user", retMap.get(BackendApiMethodEnum.USER_GETMENU.getCode()).getResults());
		}
		return "/menus/edit";
	}
	
	
	@RequestMapping(value = "/save")
	public void save(HttpServletRequest req, HttpServletResponse rsp) {
		Map<String, Object> appendMap = new HashMap<String, Object>();
		this.callApi(BackendApiMethodEnum.USER_UPDATEUSERS, appendMap, req);
	}
}
